package com.oceansoft.mobile.biz.api.controller;

import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import sun.misc.BASE64Encoder;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.oceansoft.mobile.biz.api.entity.Member;
import com.oceansoft.mobile.common.Constant;
import com.oceansoft.mobile.common.util.HttpClientUtil;
import com.oceansoft.mobile.common.util.Result;
import com.oceansoft.mobile.weixin.util.RequestUtils;
import com.oceansoft.mobile.weixin.util.WeixinUtil;

@Controller
@RequestMapping(value = "api/consult")
public class ApiConsultController {

//	private static final String host="http://221.224.13.5:8190/econsole/api/matters/";

	//private static final String host = "http://localhost:8080/econsole/api/matters/new/";

	@RequestMapping(value = "gotoPage/{pageName}")
	public String gotoPage(@PathVariable("pageName") String pageName,HttpSession sessiion,HttpServletRequest request,
						   Model model) throws IllegalArgumentException, IOException {
		boolean b = WeixinUtil.checkIsLoginUser(request);
		String source = (String) request.getSession().getAttribute("source");
	       if (!StringUtils.isEmpty(source)) {
	       	model.addAttribute("source", source);
	       }
		if(!b){
			model.addAttribute("openId",(String)sessiion.getAttribute("openId"));
			model.addAttribute("gotoPage","/api/consult/gotoPage/"+ pageName);
			return "weixin/login/login";
		}else{
			Member member = (Member)sessiion.getAttribute(Constant.SESSION_USER);
			model.addAttribute("userId",member.getGuid());
			model.addAttribute("page_size", 5);
			model.addAttribute("page_index", 1);
			 
			return "weixin/consult/" + pageName;
		}

	}
	@RequestMapping("report")
	public String gotoReport(HttpServletRequest request, Model model){
		 String source = (String) request.getSession().getAttribute("source");
	       if (!StringUtils.isEmpty(source)) {
	       	model.addAttribute("source", source);
	       }
		return "weixin/consult/report";
	}

	/**
	 * 获取我的咨询列表
	 *
	 * @param model
	 * @return
	 * @throws IOException
	 * @throws IllegalArgumentException
	 */
	@ResponseBody
	@RequestMapping(value = "page/consult", method = RequestMethod.POST)
	public Result loadConsultList(
			@RequestParam(value = "keyword", required = false, defaultValue = "") final String keywords,
			@RequestParam(value = "user_id", required = false, defaultValue = "") final String uid,
			@RequestParam(value = "question_id", required = false, defaultValue = "") final String qid,HttpSession sessiion,HttpServletRequest request)
			throws IllegalArgumentException, IOException {
		int size=0,index=0;
		String page_size=request.getParameter("page_size");
		String page_index=request.getParameter("page_index");
		if(StringUtils.isEmpty(page_size)){
			size=5;
		}else{
			size=Integer.parseInt(page_size);
		}
		if(StringUtils.isEmpty(page_index)){
			index=1;
		}else{
			index=Integer.parseInt(page_index);
		}

		String url = Constant.host5 + "api/Consult/GetConsultInfo";
		Result r = null;
		JSONObject param = new JSONObject();
    	param.put("KEYWORD",keywords);
    	param.put("PageIndex",index);
    	param.put("PageSize",size);
    	param.put("QuestionType",3);//1 网厅     	2app  	3 微信
//    	Member member = (Member)sessiion.getAttribute(Constant.SESSION_USER);
    	if(StringUtils.isNotEmpty(uid)){
    		param.put("UserGuiD", uid);
    	}
    	r = HttpClientUtil.doGAUrlPost(url, param);
		return r;

	}

	/**
	 * 咨询提交
	 *
	 * @param question
	 *            提问实体
	 * @return Result
	 */
	@ResponseBody
	@RequestMapping(value = "ask/question", method = RequestMethod.POST)
	public Result submitQuestion(@RequestParam("context") String context,@RequestParam("CreateUserID") String CreateUserID) {
		String url = "api/ask/question";
		JSONObject json=new JSONObject();
		json.put("theme", "微信咨询");
		json.put("temp1", "3");//来源 1 网厅     	2app  	3 微信
		json.put("context", context);
		json.put("CreateUserID", CreateUserID);
        Result result =  RequestUtils.saveSpecific(json, url);
		return result;
		//return new Result(Result.SUCC,"调用成功！");
	}

	/**
	 * 根据问题id找到回答
	 *
	 * @param question_id
	 *            问题id
	 * @return Result
	 */
	@ResponseBody
	@RequestMapping(value = "consult/answer/{qid}")
	public Result loadAnswerByQid(@PathVariable("qid") String question_id,
								  Model model) throws IOException {
		//	question_id = new String(question_id.getBytes("iso8859-1"), "UTF-8");
		String url = Constant.host + "/api/matters/consult/answer/" + question_id;
		Result result = JSONObject.parseObject(HttpClientUtil.doGet(url),
				Result.class);
		return result ;

	}
	@RequestMapping("uploadAttachment")
	public Result uploadAttachment(HttpServletRequest request,HttpServletResponse response,HttpSession sessiion){
		String seesionname = request.getParameter("imgname");
		String base64 = request.getParameter("base64");
		String file_base64="";
		String file_name="";
		String file_ext="";
//		System.out.println("图片:"+base64);
//		System.out.println("图片长度:"+base64.length());
//		 Map<String, String> map=(Map<String, String>) sessiion.getAttribute("zxjb");
//	      if(map!=null){
//	    	  file_base64+=(map.get("file_base64")+"|"+base64);
//				file_name+=(map.get("file_name")+"|"+(seesionname+".png"));
//				file_ext+=(map.get("file_ext")+"|"+"png");
//				
//	      }
//	      else
//	      {
//	    	   map=new HashMap<String,String>();
//	    	   file_base64=base64;
//	 	      file_name=(seesionname+".png");
//	 	      file_ext="png";
//	      }
	      
//		List<MultipartFile> files =  ((MultipartHttpServletRequest)request).getFiles("uploadfile");
//		String file_base64="";
//		String file_name="";
//		String file_ext="";
//		for (int i = 0; i < files.size(); i++) {
//			if(i>0){
//				file_base64+="|";
//				file_name+="|";
//				file_ext+="|";
//			}
//			CommonsMultipartFile file=(CommonsMultipartFile) files.get(i);
//			byte[] output =  file.getBytes();
//			
//			int maxsizefj = 150000;
//			if(output.length>maxsizefj)
//			{
//				float quality = (float)((float)maxsizefj/(float)output.length);
//				output = compressPic(output,quality);
//			}
//			BASE64Encoder encoder = new BASE64Encoder();
//			String fileType = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")+1,file.getOriginalFilename().length());
//			String fileName=file.getOriginalFilename();
//			file_base64 +=  encoder.encode(output);
//			file_name+=fileName;
//			file_ext+=fileType;
//		}
		 file_base64=base64;
	     file_name=(seesionname+".png");
	     file_ext="png";
	    Map<String, String> map=new HashMap<String,String>();
		map.put("file_base64", file_base64);
		map.put("file_name", file_name);
		map.put("file_ext", file_ext);
		//request.getSession().setAttribute("zxjb", map);
		 String url ="http://172.16.1.250/e/extend/index.php?s=api/upfile";
		 Result r = null;
		 //response1 =  {"status":1,"msg":"提交成功！","data":"1"}
//		 System.out.println(map);
		 String response1=HttpClientUtil.doPost(url, map, "utf-8");//附件上传
//	      System.out.println(StringEscapeUtils.unescapeJava(response1));
	      JSON josnJson=JSON.parseObject(StringEscapeUtils.unescapeJava(response1));
		  r=JSON.toJavaObject(josnJson, Result.class);
		  String id=r.getData()+"";//附件上传之后返回的附件id
//		  Map<String, Result> m=(Map<String, Result>) sessiion.getAttribute("zxjb");
//		  Result result = new  Result();
//		  JSONObject param = new JSONObject();
//		  param.put("file_base64", file_base64);
//			param.put("file_name", file_name);
//			param.put("file_ext",file_ext);
//		  try {
//				result = HttpClientUtil.doGAUrlPost(url, param);
//			} catch (Exception e) {
//				e.printStackTrace();
//				result.setSucc(false);
//				result.setMsg(e.getMessage());
//			}
		  Map<String ,String> m = (Map<String ,String>)request.getSession().getAttribute("zxjb");
			request.getSession().removeAttribute("zxjb");
			if(null==m)
			{
				m = new HashMap<String ,String>();
			}
			//m.put("xzfy_fj"+type, result);
			//将每张图的id放付Map中,根据图片名称的不同
			m.put(seesionname, id);
		//将图片id放入session中.
		request.getSession().setAttribute("zxjb",m);
		  
		return r;
		
//		response.setCharacterEncoding("utf-8");
//		PrintWriter writer=null;
//		try {
//			writer = response.getWriter();
//			Result r1=new Result();
//			r1.setMsg("上传成功");
//			r1.setData(map);
//			String responsestr=JSON.toJSONString(r1);
//			writer.write("<script>parent.callback("+responsestr+");</script>");
//		} catch (IOException e) {
//			e.printStackTrace();
//		}finally{
//			if(null!=writer){
//				writer.close();
//			}
//		}
	}
	 // 压缩图片的方法
 	public static byte[] compressPic(byte[] pic, float quality) {

 		ByteArrayInputStream is = new ByteArrayInputStream(pic);

 		BufferedImage src = null;
 		ByteArrayOutputStream out = null;
 		ImageWriter imgWrier;
 		ImageWriteParam imgWriteParams;

 		// 指定写图片的方式为 jpg
 		imgWrier = ImageIO.getImageWritersByFormatName("jpg").next();
 		imgWriteParams = new javax.imageio.plugins.jpeg.JPEGImageWriteParam(null);
 		// 要使用压缩，必须指定压缩方式为MODE_EXPLICIT
 		imgWriteParams.setCompressionMode(imgWriteParams.MODE_EXPLICIT);
 		// 这里指定压缩的程度，参数qality是取值0~1范围内，
 		imgWriteParams.setCompressionQuality(quality);

 		imgWriteParams.setProgressiveMode(imgWriteParams.MODE_DISABLED);
 		ColorModel colorModel = ColorModel.getRGBdefault();
 		// 指定压缩时使用的色彩模式
 		imgWriteParams.setDestinationType(new javax.imageio.ImageTypeSpecifier(colorModel, colorModel.createCompatibleSampleModel(16, 16)));

 		try {
 			src = ImageIO.read(is);
 			out = new ByteArrayOutputStream(pic.length);

 			imgWrier.reset();
 			// 必须先指定 out值，才能调用write方法, ImageOutputStream可以通过任何 OutputStream构造
 			imgWrier.setOutput(ImageIO.createImageOutputStream(out));
 			// 调用write方法，就可以向输入流写图片
 			imgWrier.write(null, new IIOImage(src, null, null), imgWriteParams);

 			out.flush();
 			out.close();
 			is.close();
 			return out.toByteArray();
 		} catch (Exception e) {
 			e.printStackTrace();
 		}
 		return null;
 	}
	/**
	 * 咨询提交
	 *
	 * @param question
	 *            提问实体
	 * @return Result
	 */
	@ResponseBody
	@RequestMapping(value = "ask/{type_id}", method = RequestMethod.POST)
	public Result submitAsk(@PathVariable("type_id") String type_id,HttpServletRequest request,HttpSession sessiion) {
	String content=request.getParameter("content");
	String figuid=request.getParameter("figuid");
//	System.out.println("content="+content);
	  String url = "http://172.16.1.250/e/extend/index.php?s=api/ask";
      Result r = null;
      Map<String, String> param= RequestUtils.buildParamsByNamesFromRequest(request);
      //String type_id=param.get("type_id");
      String title="";
      if("1".equals(type_id)){
    	  title="微信咨询";
    	  Member member = (Member)sessiion.getAttribute(Constant.SESSION_USER);
          param.put("people_name",member.getRealName());//创建人姓名
          param.put("channel_user",member.getGuid());//创建人guid
      }else if("2".equals(type_id)){
    	  title="微信投诉";
    	  Member member = (Member)sessiion.getAttribute(Constant.SESSION_USER);
          param.put("people_name",member.getRealName());//创建人姓名
          param.put("channel_user",member.getGuid());//创建人guid
      }else if("3".equals(type_id)){
    	  title="微信举报";
      }
      param.put("title",title);
//      Map<String, String> map=(Map<String, String>) sessiion.getAttribute("zxjb");
//      if(map!=null){
//    	  param.putAll(map);
//      }
//      
      //附件Id
      Map<String ,String> m = (Map<String ,String>)sessiion.getAttribute("zxjb");
      sessiion.removeAttribute("zxjb");
//      if(null==m||m.isEmpty())
//      {
//          return new Result(false);
//      }
      //String fjguid ="";
      //循环读取附件
//      Set<String> fjkeys = m.keySet();
//      for (String key : fjkeys) {
//          Result r1 = m.get(key);
//          fjguid+= ((JSONObject)r1.getData())+",";
//         
//      }
    //循环读取附件id,根据图片名称
    /*  if(null==m||m.isEmpty())
      {
    	  fjguid="";
      }
      else
      {
    	  for(int i=0;i<m.size();i++)
          {
        	  if(i>0)
        	  {
        		  fjguid += ",";
        	  }
        	  fjguid+=m.get("fj"+(i+1));
        	  
          }
      }*/
//      System.out.println(fjguid);
      param.put("upfiles",figuid);
//      System.out.println("param==="+param);
      
      String response=HttpClientUtil.doPost(url, param, "utf-8");
//      try {
//    	  Result r1 = HttpClientUtil.doGAUrlPost(url, RequestUtils.map2Json(param));
//	} catch (IOException e) {
//		// TODO Auto-generated catch block
//		e.printStackTrace();
//	}
//      System.out.println(StringEscapeUtils.unescapeJava(response));
      JSON josnJson=JSON.parseObject(StringEscapeUtils.unescapeJava(response));
	  r=JSON.toJavaObject(josnJson, Result.class);
	  sessiion.removeAttribute("zxjb");
      return r;
	}
	/**
	 * 违法犯罪提交方法
	 * @param type_id
	 * @param request
	 * @param sessiion
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "askwf/{type_id}", method = RequestMethod.POST)
	public Result submitAskWF(@PathVariable("type_id") String type_id,HttpServletRequest request,HttpSession sessiion) {
	String content=request.getParameter("content");
	String figuid=request.getParameter("figuid");
//	System.out.println("content="+content);
	  String url = "http://172.16.1.250/e/extend/index.php?s=api/ask";
      Result r = null;
      Map<String, String> param= RequestUtils.buildParamsByNamesFromRequest(request);
      //String type_id=param.get("type_id");
      String title="";
      if("1".equals(type_id)){
    	  title="微信咨询";
    	  Member member = (Member)sessiion.getAttribute(Constant.SESSION_USER);
          param.put("people_name",member.getRealName());//创建人姓名
          param.put("channel_user",member.getGuid());//创建人guid
      }else if("2".equals(type_id)){
    	  title="微信投诉";
    	  Member member = (Member)sessiion.getAttribute(Constant.SESSION_USER);
          param.put("people_name",member.getRealName());//创建人姓名
          param.put("channel_user",member.getGuid());//创建人guid
      }else if("3".equals(type_id)){
    	  title="微信举报";
      }
      param.put("title",title);
//      Map<String, String> map=(Map<String, String>) sessiion.getAttribute("zxjb");
//      if(map!=null){
//    	  param.putAll(map);
//      }
//      
      //附件Id
      Map<String ,String> m = (Map<String ,String>)sessiion.getAttribute("zxjb");
      sessiion.removeAttribute("zxjb");
//      if(null==m||m.isEmpty())
//      {
//          return new Result(false);
//      }
    /*  String fjguid ="";
    //循环读取附件id,根据图片名称
      if(null==m||m.isEmpty())
      {
    	  fjguid="";
      }
      else
      {
    	  for(int i=0;i<m.size();i++)
          {
        	  if(i>0)
        	  {
        		  fjguid += ",";
        	  }
        	  fjguid+=m.get("fj"+(i+1));
        	  
          }
      }
      */
//      System.out.println(fjguid);
      param.put("upfiles",figuid);
//      System.out.println("param==="+param);
      
      String response=HttpClientUtil.doPost(url, param, "utf-8");
//      try {
//    	  Result r1 = HttpClientUtil.doGAUrlPost(url, RequestUtils.map2Json(param));
//	} catch (IOException e) {
//		// TODO Auto-generated catch block
//		e.printStackTrace();
//	}
//      System.out.println(StringEscapeUtils.unescapeJava(response));
      JSON josnJson=JSON.parseObject(StringEscapeUtils.unescapeJava(response));
	  r=JSON.toJavaObject(josnJson, Result.class);
	  sessiion.removeAttribute("zxjb");
      return r;
	}
	/**
	 * 获取我的咨询列表-新接口
	 *
	 * @param model
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "page/consultlist", method = RequestMethod.POST)
	public Result getConsultList(HttpSession sessiion, HttpServletRequest request){
		int size = 0, index = 0;
		String page_size = request.getParameter("page_size");
		String keywords=request.getParameter("keyword");
		String uid=request.getParameter("user_id");
		String type_id = request.getParameter("type_id");
//		System.out.println("type_id="+type_id);
		if (StringUtils.isEmpty(page_size)) {
			size = 5;
		} else {
			size = Integer.parseInt(page_size);
		}
		String search_type=request.getParameter("search_type");
		String page_index="1";
		if("zx".equals(search_type)){
			page_index = request.getParameter("page_index_zx");
		}else if("ts".equals(search_type)){
			page_index = request.getParameter("page_index_ts");
		}else if("zxts".equals(search_type)){
			page_index = request.getParameter("page_index_zxts");
		}else{
			page_index = request.getParameter("page_index");
		}
		if (StringUtils.isEmpty(page_index)) {
			index = 1;
		} else {
			index = Integer.parseInt(page_index);
		}
		String url = "http://172.16.1.250/e/extend/index.php?s=api/getask";
		Result r = null;
		Map<String, String> param = new HashMap<String, String>();
		param.put("keyword", keywords);
		param.put("type_id", type_id);
		param.put("page", index+"");
		param.put("pagerows", size+"");
		param.put("channel_id", "4");// 1 网厅 2app 3 微信
		if (StringUtils.isNotEmpty(uid)) {
			param.put("channel_user", uid);
		}
		String response = HttpClientUtil.doPost(url, param, "utf-8");
//		System.out.println(StringEscapeUtils.unescapeJava(response));
		JSON josnJson = JSON.parseObject(StringEscapeUtils
				.unescapeJava(response));
		r = JSON.toJavaObject(josnJson, Result.class);
		return r;
	}
}
